package com.yjzx.binlog.config;


import com.yjzx.util.binlog.core.config.BinLogBean;
import com.yjzx.util.binlog.core.entiry.recordIndex.BinaryLogClientIndex;
import com.yjzx.util.binlog.core.entiry.recordIndex.FileRecordBinLogIndex;
import com.yjzx.util.binlog.core.entiry.recordIndex.MemoryRecordBinLogIndex;
import com.yjzx.util.binlog.core.constants.BinLogIndexConstant;
import com.yjzx.util.binlog.core.util.BinLogUtils;
import com.yjzx.util.binlog.core.util.StringUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yjzx
 * @date 2024/7/6
 * @description 配置文件注册
 */
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "binlog")
public class BinLogProperties {

    private BinLogBean properties = new BinLogBean();
    private Map<String, Map<String, Object>> index;

    /**
     * 配置文件转换为配置Bean
     * @return
     */
    public BinLogBean toBinLogBean() {
        String binfile = null, recordfile = null;
        Long position = null;
        if (index==null){
            index=new HashMap<>();
        }
        BinaryLogClientIndex index1 = loadMemoryRecordBinLogIndex(position, binfile);

        BinaryLogClientIndex index2 = loadFileRecordBinLogIndex(recordfile);

        BinLogUtils.toFileRecordBinLogIndex(properties, index1, index2);
        return properties;
    }

    private BinaryLogClientIndex loadFileRecordBinLogIndex(String recordfile) {
        Map<String, Object> file = index.get(BinLogIndexConstant.INDEX_NAME_FILE);
        if (file != null) {
            recordfile = (String) file.get(BinLogIndexConstant.INDEX_NAME_FILE_RECORD_FILE);
        }
        return new FileRecordBinLogIndex(StringUtils.isBlank(recordfile) ? null : recordfile);
    }

    private MemoryRecordBinLogIndex loadMemoryRecordBinLogIndex(Long position, String binfile) {
        Map<String, Object> memory = index.get(BinLogIndexConstant.INDEX_NAME_MEMORY);
        if (memory != null) {
            Object position1 = memory.get(BinLogIndexConstant.INDEX_NAME_MEMORY_POSITION);
            position = position1 instanceof Number ? ((Number) position1).longValue() : position1 instanceof String ? Long.parseLong((String) position1) : null;
            binfile = (String) memory.get(BinLogIndexConstant.INDEX_NAME_MEMORY_BIN_FILE);
        }
        return new MemoryRecordBinLogIndex(StringUtils.isBlank(binfile) ? null : binfile, position == null || position <= 0 ? null : position);
    }

}
